package cn.jbit.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;




public class BaseDao {
	protected  Connection conn;
	protected  PreparedStatement pstmt;
	protected  ResultSet rs;
	/**
	 * 获取数据库链接对象
	 * @return
	 */
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/test?"
					+ "user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
			conn=DriverManager.getConnection(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return conn;
	}
	/**
	 * 关闭数据库
	 * @param conn
	 * @param stmt
	 * @param rs
	 */
	public void closeAll(Connection conn,Statement stmt,ResultSet rs){
		//若结果集不为空，则关闭
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//若Statement对象不为空，则关闭
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//若数据库链接对象不为空，则关闭
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
		/**
		 * 此方法删除后不影响结果
		 * 增删改操作
		 * @param sql sql语句
	     * @param prams 参数数组
	     * @return 执行结果
		 */
		public  int exceuteUpdate(String sql,Object...prams){
			int result=0;
			conn=getConnection();
			try {
				pstmt=conn.prepareStatement(sql);
				for(int i=0;i<prams.length;i++){
					pstmt.setObject(i+1, prams[i]);	
				}
				result=pstmt.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				closeAll(conn, pstmt, rs);
			}
			return result;
			
		}

}
